﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

/// <summary/>
[Serializable]
[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = true, IsFixedLength = true, MaxByteSize = 8)]
public struct FullDateTime : INullable, IBinarySerialize
{
	private long _Ticks;

	/// <summary/>
	public override bool Equals(object obj)
	{
		if (obj is FullDateTime)
		{
			var fdt = (FullDateTime)obj;
			if (fdt._Ticks == this._Ticks)
				return true;

			return false;
		}

		if (obj is DateTime)
		{
			var dt = (DateTime)obj;
			if (dt.Ticks == this._Ticks)
				return true;

			return false;
		}

		return this._Ticks.Equals(obj);
	}

	/// <summary/>
	public override int GetHashCode()
	{
		//return base.GetHashCode();
		return this._Ticks.GetHashCode();
	}

	/// <summary/>
	public override string ToString()
	{
		if (this._Ticks >= 0)
			return new DateTime(this._Ticks).ToString();

		return string.Empty;
	}

	/// <summary/>
	public long Ticks
	{
		set
		{
			this._Ticks = value;
		}
		get
		{
			return this._Ticks;
		}
	}

	/// <summary/>
	public bool IsNull
	{
		get
		{
			if (this._Ticks > 0)
				return false;

			return true;
		}
	}

	/// <summary/>
	public int Year
	{
		get
		{
			return new DateTime(this._Ticks).Year;
		}
	}

	/// <summary/>
	public int Month
	{
		get
		{
			return new DateTime(this._Ticks).Month;
		}
	}

	/// <summary/>
	public int Day
	{
		get
		{
			return new DateTime(this._Ticks).Day;
		}
	}

	/// <summary/>
	public int Hour
	{
		get
		{
			return new DateTime(this._Ticks).Hour;
		}
	}

	/// <summary/>
	public int Minute
	{
		get
		{
			return new DateTime(this._Ticks).Minute;
		}
	}

	/// <summary/>
	public int Second
	{
		get
		{
			return new DateTime(this._Ticks).Second;
		}
	}

	/// <summary/>
	public int Millisecond
	{
		get
		{
			return new DateTime(this._Ticks).Millisecond;
		}
	}

	/// <summary/>
	public int DayOfWeek
	{
		get
		{
			return (int)(new DateTime(this._Ticks).DayOfWeek);
		}
	}

	/// <summary/>
	public int DayOfYear
	{
		get
		{
			return new DateTime(this._Ticks).DayOfYear;
		}
	}

	/// <summary/>
	public static FullDateTime Null
	{
		get
		{
			return new FullDateTime { Ticks = long.MinValue };
		}
	}

	/// <summary/>
	public static FullDateTime Parse(SqlString s)
	{
		if (s.IsNull)
			return new FullDateTime { Ticks = long.MinValue };

		return new FullDateTime { Ticks = DateTime.Parse(s.Value).Ticks };
	}

	/// <summary/>
	public void Read(System.IO.BinaryReader r)
	{
		this._Ticks = r.ReadInt64();
	}

	/// <summary/>
	public void Write(System.IO.BinaryWriter w)
	{
		w.Write(this._Ticks);
	}
}


